package cn.xinfei.xdecision.common.service.component.componentaction.impl;

import cn.xinfei.xdecision.common.dao.component.componentaction.ComponentActionMapper;
import cn.xinfei.xdecision.common.model.component.ComponentAction;
import cn.xinfei.xdecision.common.service.component.componentaction.ComponentActionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class ComponentActionServiceImpl extends ServiceImpl<ComponentActionMapper, ComponentAction> implements ComponentActionService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateComponentAction(List<ComponentAction> componentActionList, String componentCode, String componentType, Long versionNo) {
//        componentActionList.forEach(x -> x.setComponentCode(componentCode).setVersionNo(versionNo));
//        //找出需要删除的id
//        List<ComponentAction> oldComponentActions = this.list(new LambdaQueryWrapper<ComponentAction>()
//                .eq(ComponentAction::getComponentCode, componentCode)
//                .eq(ComponentAction::getVersionNo, versionNo));
//        Predicate<ComponentAction> predicate = a -> componentActionList.stream().noneMatch(b -> a.getId().equals(b.getId()));
//        List<Long> needDeleteIds = oldComponentActions.stream().filter(predicate).map(ComponentAction::getId).collect(Collectors.toList());
//        this.removeByIds(needDeleteIds);
//        //save or update
//        this.saveOrUpdateBatch(componentActionList);
        //先删，后加
        this.remove(new LambdaQueryWrapper<ComponentAction>()
                .eq(ComponentAction::getComponentCode, componentCode)
                .eq(ComponentAction::getVersionNo, versionNo));
        if (!CollectionUtils.isEmpty(componentActionList)) {
            componentActionList.forEach(x ->
                    x.setComponentCode(componentCode)
                            .setComponentType(componentType)
                            .setVersionNo(versionNo)
                            .setId(null));
            this.saveBatch(componentActionList);
        }
    }

    @Override
    public List<ComponentAction> getComponentActionByComponentCode(String componentCode, Long versionNo, List<String> componentTypeList) {
        LambdaQueryWrapper<ComponentAction> lbd = new LambdaQueryWrapper<ComponentAction>()
                .eq(ComponentAction::getComponentCode, componentCode)
                .eq(ComponentAction::getVersionNo, versionNo);
        if (!CollectionUtils.isEmpty(componentTypeList)) {
            lbd.in(ComponentAction::getComponentType, componentTypeList);
        }
        return this.list(lbd);
    }
}
